package com.zhuqieli.database_learn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuqieli.database_learn.common.Result;
import com.zhuqieli.database_learn.dao.UserTableMapper;
import com.zhuqieli.database_learn.pojo.UserTable;
import com.zhuqieli.database_learn.service.UserTableService;
import com.zhuqieli.database_learn.utils.BcryptUtil;
import com.zhuqieli.database_learn.utils.JwtUtil;
import com.zhuqieli.database_learn.utils.MyException;
import com.zhuqieli.database_learn.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author dupr
 * @description 用户服务实现类
 * @date 2023/8/30 19:52:19
 */

@Service
public class UserTableServiceImpl extends ServiceImpl<UserTableMapper, UserTable> implements UserTableService {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtils redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public UserTable login(String phoneNumber, String password) {

        // 先从数据库查询
        UserTable userTable = this.getOne(new QueryWrapper<UserTable>().eq("phone_number", phoneNumber));
        if (null == userTable) {
            UserTable erUserTable = UserTable.builder().phoneNumber("99999999999").build();
            return erUserTable;
        }
        if (!BcryptUtil.match(password, userTable.getPassword())) {
            UserTable erUserTable = UserTable.builder().phoneNumber("88888888888").build();
            return erUserTable;
        }
        String jwtToken = jwtUtil.createJwtToken(userTable.getId().toString(), 10 * 10);
        redisTemplate.opsForValue().set("token_" + jwtToken, userTable, 60 * 10, TimeUnit.SECONDS);
        //用password字段暂存token
        userTable.setPassword(jwtToken);
        return userTable;
    }
}
